package org.csu.wuliu.controller;

//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import org.csu.wuliu.domain.*;
import org.csu.wuliu.persistence.CategoryMapper;
import org.csu.wuliu.persistence.ItemMapper;
import org.csu.wuliu.persistence.LineItemMapper;
import org.csu.wuliu.persistence.ProductMapper;
import org.csu.wuliu.service.CatalogService;
import org.csu.wuliu.service.OrderService;
import org.csu.wuliu.service.TaskService;
import org.csu.wuliu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/orders")
@ResponseBody
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private LineItemMapper lineItemMapper;

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private TaskService taskService;


    /**
     {
     "lineItems": [
     {
     "itemId": "1",
     "number": 10,
     "itemName": "item1",
     "listprice": 50.0,
     "orderId": "OD202007110001",
     "productName": "二级1"
     },
     {
     "itemId": "2",
     "number": 5,
     "itemName": "item2",
     "listprice": 20.0,
     "orderId": "OD202007110001",
     "productName": "二级1"
     },
     {
     "itemId": "3",
     "number": 4,
     "itemName": "item3",
     "listprice": 100.0,
     "orderId": "OD202007110001",
     "productName": "二级1"
     }
     ],
     "address": "重庆",
     "orderId": "OD202007110001",
     "totalprice": 1000.0,
     "tel": "15736076132",
     "orderDate": "2020-07-10T16:00:00.000+00:00",
     "username": "wunanxi",
     "status": 1
     }
     */

    @GetMapping("/view")
    public JSONObject getOrder(@RequestParam String orderId){
        JSONObject json = new JSONObject();
        Order order = orderService.getOrder(orderId);
        if(order==null){
            String msg = "该订单不存在";
            json.put("message",msg);
            return json;
        }
        else{
            json.put("orderId",order.getOrderId());
            String username = order.getUsername();
            User user = userService.getUserByusername(username);
            json.put("user",user);
            json.put("orderDate",order.getOrderDate());
            json.put("status",order.getStatus());
            json.put("address",user.getAddress());
            json.put("tel",user.getTel());
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(orderId);
            System.out.println(lineItems);
            BigDecimal count = new BigDecimal("0");
            json.put("lineItems",lineItems);
            JSONArray jsonArray = new JSONArray();
            for(LineItem lineItem:lineItems){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("itemId",lineItem.getItemId());
                jsonObject.put("orderId",lineItem.getOrderId());
                jsonObject.put("listprice",lineItem.getListprice());
                jsonObject.put("number",lineItem.getNumber());
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                jsonObject.put("itemName",item.getName());
                Product product = catalogService.getProduct(item.getProductId());
                jsonObject.put("productName",product.getName());
                jsonArray.add(jsonObject);
                count = count.add(lineItem.calculateTotal());
            }
            json.put("totalprice",count);
            json.put("lineItems",jsonArray);
            return  json;}
    }


    /**
     *
     * @return
     * [
     *     {
     *         "lineItems": [
     *             {
     *                 "orderId": "OD202007110001",
     *                 "itemId": "1",
     *                 "number": 10,
     *                 "listprice": 50.0
     *             },
     *             {
     *                 "orderId": "OD202007110001",
     *                 "itemId": "2",
     *                 "number": 5,
     *                 "listprice": 20.0
     *             },
     *             {
     *                 "orderId": "OD202007110001",
     *                 "itemId": "3",
     *                 "number": 4,
     *                 "listprice": 100.0
     *             }
     *         ],
     *         "total": 1000.0,
     *         "order": {
     *             "orderId": "OD202007110001",
     *             "username": "wunanxi",
     *             "orderDate": "2020-07-10T16:00:00.000+00:00",
     *             "status": 1
     *         }
     *     },
     *     {
     *         "lineItems": [],
     *         "total": 0,
     *         "order": {
     *             "orderId": "OD202007120001",
     *             "username": "风雪",
     *             "orderDate": "2020-07-11T16:00:00.000+00:00",
     *             "status": 1
     *         }
     *     },
     *     {
     *         "lineItems": [],
     *         "total": 0,
     *         "order": {
     *             "orderId": "OD202007120002",
     *             "username": "wunanxi",
     *             "orderDate": "2020-07-11T16:00:00.000+00:00",
     *             "status": 1
     *         }
     *     }
     * ]
     */

    @GetMapping("/viewAllOrders")
    public JSONArray getOrders(){
        JSONArray jsonList = new JSONArray();
        List<Order> orderList = orderService.getOrders();
        for(Order order:orderList) {
            JSONObject json = new JSONObject();
            BigDecimal count = new BigDecimal("0");
            JSONArray lineItemList = new JSONArray();
            System.out.println(order.getOrderId());
            json.put("order",order);
            User user  = userService.getUserByusername(order.getUsername());
            json.put("user",user);
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
            for (LineItem lineItem : lineItems) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("itemId",lineItem.getItemId());
                jsonObject.put("orderId",lineItem.getOrderId());
                jsonObject.put("listprice",lineItem.getListprice());
                jsonObject.put("number",lineItem.getNumber());
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                jsonObject.put("itemName",item.getName());
                Product product = catalogService.getProduct(item.getProductId());
                jsonObject.put("productName",product.getName());
                lineItemList.add(jsonObject);
                count = count.add(lineItem.calculateTotal());
            }
            json.put("lineItems",lineItemList);
            json.put("totalprice",count);
            System.out.println("count:"+count);
            jsonList.add(json);
        }
        return jsonList;
    }



    /** 请求体 {
     "username":"hkx",
     "lineItems": [{
     "itemId":"1",
     "number":"50",
     "listprice":"50.0"

     },
     {
     "itemId":"2",
     "number":"10",
     "listprice":"20.0"
     }]}
     */



    @PostMapping("/add")
    public JSONObject newOrder(@RequestBody String jsonString){
        JSONObject json = JSONObject.parseObject(jsonString);
        JSONArray jsonList = new JSONArray();
        JSONObject json2 = new JSONObject();
        Order order = new Order();
        order.setOrderId(orderService.autoCreated());
        order.setUsername(json.getString("username"));
        order.setOrderDate(order.getOrderDate());
        boolean temp = true;
        BigDecimal count = new BigDecimal(0);
        User user = userService.getUserByusername(json.getString("username"));
        JSONArray lineItemList = json.getJSONArray("lineItems");
        order.setStatus(2);
        orderService.insertOrder(order);
        for (Object lineItem : lineItemList) {
            LineItem lineItem1 = new LineItem();
            lineItem1.setOrderId(order.getOrderId());
            lineItem1.setItemId(((JSONObject)lineItem).getString("itemId"));
            lineItem1.setListprice(((JSONObject)lineItem).getBigDecimal("listprice"));
            lineItem1.setNumber(((JSONObject)lineItem).getInteger("number"));
            lineItemMapper.insertLineItem(lineItem1);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("itemId",lineItem1.getItemId());
            jsonObject.put("orderId",lineItem1.getOrderId());
            jsonObject.put("listprice",lineItem1.getListprice());
            jsonObject.put("number",lineItem1.getNumber());
            String itemId = lineItem1.getItemId();
            Item item = itemMapper.getItem(itemId);
            jsonObject.put("itemName",item.getName());
            Product product = catalogService.getProduct(item.getProductId());
            jsonObject.put("productName",product.getName());
            count = count.add(lineItem1.calculateTotal());
            jsonList.add(jsonObject);
            if(item.getStock()-lineItem1.getNumber()<0&&temp){
                order.setStatus(0);
                temp = false;
            }
        }
        if(!temp)
            orderService.updateOrder(order);
        json2.put("order",order);
        json2.put("user",user);
        json2.put("lineItems",jsonList);
        json2.put("totalprice",count);
        //下达订单的同时生成任务单
        taskService.autoCreated(order.getOrderId());
        return json2;
    }


    //{
    //   "orderId" : "OD202007110002",
    //   "status" : 2
    //
    //}

    //修改订单信息功能
    @PostMapping("/update")
    public ResponseEntity<String> updateOrderStatus(@RequestBody String jsonString){
        JSONObject json = JSONObject.parseObject(jsonString);
        Order order = new Order();
        order.setOrderId(json.getString("orderId"));
        order.setStatus(json.getInteger("status"));
        orderService.updateOrder(order);
        return new ResponseEntity<String>("您的订单已经修改", HttpStatus.OK);
    }



//    @GetMapping("/{orderId}")
//    public Order viewOrder(@PathVariable String orderId){
//        return orderService.getOrder(orderId);
//    }

//    @PostMapping("/search")
//    public List<Order> viewOrderList(@RequestParam String keyword){
//        return orderService.searchOrderList(keyword);
//    }


    /*
    请求{"status" : 1}
    响应[
    {
        "lineItems": [
            {
                "orderId": "OD202007110001",
                "itemId": "1",
                "number": 10,
                "listprice": 50.0
            },
            {
                "orderId": "OD202007110001",
                "itemId": "2",
                "number": 5,
                "listprice": 20.0
            },
            {
                "orderId": "OD202007110001",
                "itemId": "3",
                "number": 4,
                "listprice": 100.0
            }
        ],
        "total": 1000.0,
        "order": {
            "orderId": "OD202007110001",
            "username": "wunanxi",
            "orderDate": "2020-07-10T16:00:00.000+00:00",
            "status": 1
        }
    },
    {
        "lineItems": [],
        "total": 0,
        "order": {
            "orderId": "OD202007120001",
            "username": "风雪",
            "orderDate": "2020-07-11T16:00:00.000+00:00",
            "status": 1
        }
    },
    {
        "lineItems": [],
        "total": 0,
        "order": {
            "orderId": "OD202007120002",
            "username": "wunanxi",
            "orderDate": "2020-07-11T16:00:00.000+00:00",
            "status": 1
        }
    }
]
     */

    @PostMapping("/status")
    public JSONArray viewOrderByStatus(@RequestBody String jsonString){
        JSONObject json1 = JSONObject.parseObject(jsonString);
        int status = json1.getInteger("status");
        JSONArray jsonList = new JSONArray();
        List<Order> orderList = orderService.getOrdersByOrderStatus(status);
        for(Order order:orderList) {
            JSONObject json = new JSONObject();
            BigDecimal count = new BigDecimal("0");
            JSONArray lineItemList = new JSONArray();
            json.put("order",order);
            User user  = userService.getUserByusername(order.getUsername());
            json.put("user",user);
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
            for (LineItem lineItem : lineItems) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("itemId",lineItem.getItemId());
                jsonObject.put("orderId",lineItem.getOrderId());
                jsonObject.put("listprice",lineItem.getListprice());
                jsonObject.put("number",lineItem.getNumber());
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                jsonObject.put("itemName",item.getName());
                Product product = catalogService.getProduct(item.getProductId());
                jsonObject.put("productName",product.getName());
                count = count.add(lineItem.calculateTotal());
                lineItemList.add(jsonObject);
            }
            json.put("lineItems", lineItemList);
            json.put("totalprice", count);
            jsonList.add(json);
        }
        return jsonList;
    }




    @PostMapping("/Date")
    public JSONArray viewOrderByDates(@RequestBody String jsonString) {
        JSONObject json1 = JSONObject.parseObject(jsonString);
        String temp_date = json1.getString("date");
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String dateStr = formatter.format(temp_date);
//        Date date = formatter.parse(temp_date);
        JSONArray jsonList = new JSONArray();
        List<Order> orderList = orderService.getOrdersByOrderDate(temp_date);
        for(Order order:orderList) {
            JSONObject json = new JSONObject();
            BigDecimal count = new BigDecimal("0");
            JSONArray lineItemList = new JSONArray();
            json.put("order",order);
            User user  = userService.getUserByusername(order.getUsername());
            json.put("user",user);
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
            for (LineItem lineItem : lineItems) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("itemId",lineItem.getItemId());
                jsonObject.put("orderId",lineItem.getOrderId());
                jsonObject.put("listprice",lineItem.getListprice());
                jsonObject.put("number",lineItem.getNumber());
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                jsonObject.put("itemName",item.getName());
                Product product = catalogService.getProduct(item.getProductId());
                jsonObject.put("productName",product.getName());
                lineItemList.add(jsonObject);
                count = count.add(lineItem.calculateTotal());
            }
            json.put("lineItems", lineItemList);
            json.put("totalprice", count);
            jsonList.add(json);
        }
        return jsonList;
    }

    //通过username查询订单
    //返回格式
    /**[
     {
     "lineItems": [
     {
     "orderId": "OD202007110001",
     "itemId": "1",
     "number": 10,
     "listprice": 50.0
     },
     {
     "orderId": "OD202007110001",
     "itemId": "2",
     "number": 5,
     "listprice": 20.0
     },
     {
     "orderId": "OD202007110001",
     "itemId": "3",
     "number": 4,
     "listprice": 100.0
     }
     ],
     "total": 1000.0,
     "order": {
     "orderId": "OD202007110001",
     "username": "wunanxi",
     "orderDate": "2020-07-10T16:00:00.000+00:00",
     "status": 1
     }
     },
     {
     "lineItems": [],
     "total": 0,
     "order": {
     "orderId": "OD202007120002",
     "username": "wunanxi",
     "orderDate": "2020-07-11T16:00:00.000+00:00",
     "status": 1
     }
     }
     ]
     */
    @PostMapping("/username")
    public JSONObject viewOrderByUsername(@RequestBody String JSONString){
        JSONObject json1 = JSONObject.parseObject(JSONString);
        JSONObject json2 = new JSONObject();
        String username = json1.getString("username");
        User user  = userService.getUserByusername(username);
        json2.put("user",user);
        JSONArray jsonList = new JSONArray();
        System.out.println(username);
        List<Order> orderList = orderService.getOrdersByUsername(username);
        for(Order order:orderList) {
            JSONObject json = new JSONObject();
            BigDecimal count = new BigDecimal("0");
            JSONArray lineItemList = new JSONArray();
            System.out.println(order.getOrderId());
            json.put("order",order);
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
            for (LineItem lineItem : lineItems) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("itemId",lineItem.getItemId());
                jsonObject.put("orderId",lineItem.getOrderId());
                jsonObject.put("listprice",lineItem.getListprice());
                jsonObject.put("number",lineItem.getNumber());
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                jsonObject.put("itemName",item.getName());
                Product product = catalogService.getProduct(item.getProductId());
                jsonObject.put("productName",product.getName());
                lineItemList.add(jsonObject);
                count = count.add(lineItem.calculateTotal());
            }
            json.put("lineItems", lineItemList);
            json.put("totalprice", count);
            jsonList.add(json);
        }
        json2.put("orders",jsonList);
        return json2;
    }




}